<template>
	<view class="page-index">
		<view class="top">
			<image class="top-img" src="./../../static/newImg/top_background.png" mode="widthFix"></image>
			<view class="switch" @click="setSwitch"
				:style='{textAlign: switch_state ? "right" : "left" , color: switch_state ? "#125bff" : "#ffffff", backgroundColor: switch_state ? "#ffffff" : "#125bff", }'>
				<text class="txt">{{ switch_state ? '标准版' : '适老版'}}</text>
				<text class="circular" :style='{right: switch_state ? "124rpx" : "0rpx",  }'></text>
			</view>
			<view class="top-text">
				<text>萧山政务服务</text>
				<text>- 网上一站办 大厅就近办 -</text>
			</view>
		</view>
		<view class="user-info" v-if="!!Object.keys(userInfo).length">
			<text>{{userInfo.name.replaceStr(0,1)}}</text>
			<text>{{userInfo.phone.replaceStr(3,4)}}</text>
		</view>
		<view class="server-item">
			<view class="item" @click="goTask(1)">
				<image :src="img1" mode=""></image>
				<text>预约取号</text>
			</view>
			<view class="item" @click="goTask(2)">
				<image :src="img2" mode=""></image>
				<text>实时取号</text>
			</view>
			<view class="item" @click="goHistory()">
				<image :src="img3" mode=""></image>
				<text>查看进度</text>
			</view>
		</view>
		<view class="bottom">
			<image class="bottom-img" src="./../../static/newImg/bottom_background.png" mode="widthFix"></image>
			<view class="bottom-text">
				<text>一切为了群众</text>
				<text>一切方便群众</text>
			</view>
		</view>
		<view class="footer f-old">
			<text>本服务由浙江政务服务网、萧山区行政审批服务管理办公室提供</text>
			<text>服务咨询热线：<text @click="goTel('0571-82899123')" class="tel">0571-82899123</text></text>
		</view>
	</view>
</template>
<script>
	import {
		_debounce
	} from "../../utils/util.js"
	export default {
		data() {
			return {
				img1: './../../static/newImg/reserve.png',
				img2: './../../static/newImg/real_time.png',
				img3: './../../static/newImg/schedule.png',
				userInfo: {},
				switch_state: false
			};
		},
		onLoad() { 
			window.addEventListener(
				"pageshow",
				function(event) {
					if (
						event.persisted ||
						(window.performance && window.performance.navigation.type == 2)
					) {
						ZWJSBridge.onReady(() => {
							ZWJSBridge.close();
							return;
						});
					}
				},
				false
			);
			this.newLoad();
			ZWJSBridge.onReady(() => {
				ZWJSBridge.getUiStyle().then((result) => {
					if (result.uiStyle == 'elder') {
						this.switch_state = true;
					}
				});
			});
		},
		methods: {
			newLoad(){
				const sUserAgent = window.navigator.userAgent.toLowerCase();
				const isEnvironment = window.location.search.substr(1).split("&").find(i => { return i.split("=")[0] == "ticketId"}) ? 'weChat' : 'browser';
				const bIsDtDreamApp = sUserAgent.indexOf("dtdreamweb") > -1; // 浙里办APP
				const bIsAlipayMini = sUserAgent.indexOf("miniprogram") > -1 && sUserAgent.indexOf("alipay") > -1; // 浙里办支付宝小程序
				if(bIsAlipayMini){
					// 支付宝环境
					this.mobileLogin('alipay');
				}
				if(bIsDtDreamApp){
					// 浙里办环境
					this.mobileLogin('mobile');
				}
				if(isEnvironment == 'weChat'){
					// 微信环境
					this.isLoad();
				}
			},
			async isLoad(){
				let that = this;
				if (ZWJSBridge.ssoTicket) {
					const ssoFlag = await ZWJSBridge.ssoTicket({});
					if (ssoFlag && ssoFlag.result === true) {
						//使用 IRS“浙里办”单点登录组件
						if(ssoFlag.ticketId){
							// TODO 应用方服务端单点登录接口 
							that.weChatLoad();
						}else{
							//当“浙里办”单点登录失败或登录态失效时调用 ZWJSBridge.openLink 方法重 新获取 ticketId。
							ZWJSBridge.onReady(() => {
								ZWJSBridge.openLink({url: "https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2002238523/reserved/index.html"}).then(res=>{res.ticketId}) 
							});
						}
						
					} else {
						//使用 IRS【个人/法人单点登录】组件 
						this.newLoad();
					}
				} else {
					//使用 IRS【个人/法人单点登录】组件 
					this.newLoad();
				}
			},
			weChatLoad(){
				let that = this;
				let ticket = window.location.search ? window.location.search.substr(1).split("&").find(i => { return i.split("=")[0] == "ticketId"}).split("=")[1] : "";
				uni.setStorageSync("ticket", ticket);
				that.$http.get('zhdt/weixin/getToken', {
					ticket
				}).then(res => {
					console.log(res, '获取token')
					if (res.data.success) {
						let token = res.data.data;
						uni.setStorageSync("token", token);
						uni.hideLoading();
						that.$http.get('zhdt/weixin/getUserInfo', {
							token
						}).then(info => {
							console.log(info.data.data, '获取用户信息')
							that.userInfo = info.data.data;
							uni.setStorageSync("userInfo", info.data.data);
							// 埋点
							let aplusUserInfo = {
								nick: info.data.data.name,
								id: info.data.data.userid,
							};
							that.zwLoguserInfo(aplusUserInfo);
						})
					} else {
						ZWJSBridge.onReady(() => {
							ZWJSBridge.openLink({url: "https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2002238523/reserved/index.html"}).then(res=>{res.ticketId}) 
						});
					}
				})
			},
			zwLoguserInfo(userInfo){
				const zwlog = new ZwLog({ 
					_user_id: userInfo.id, 
					_user_nick: userInfo.nick,
				})
				//onReady 表示 zwlog 加载完成后的函数，它接收一个匿名函数，而 sendPV 与 record 方法均要 在匿名函数内调用。eg: 
				zwlog.onReady(function () {
					zwlog.sendPV({
						miniAppId: '2002238523', 
						Page_duration: '9', 
						t2: '33',  
						t0: '18',
						log_status: '2002238523' ,
					});
					zwlog.record('yourTrackerEventCode', 'CLK', { Test1: '测试参数 1', });
					let { metaInfo } = zwlog; // SDK 元配置的当前设置
				})
				//record⽅法将发送⼀条事件⽇志，它接收三个参数： 
				//trackerEventCode：为注册的事件编码. 当上报的事件为 PV 事件时,trackerEventCode 可传 空值或'PageView'常量； 
				//eventType：时间类型 取值为'EXP':⾃定义曝光事件/'CLK':⾃定义点击事件/'OTHER': 其他 ⾃定义事件； 
				//eventParams： 为本次事件中上报的事件参数. 其取值为⼀个 JSON 对象（平铺的简单对象， 不能多层嵌套）； 
				//JSON 中的 key 不能是以下保留属性：uidaplus,spm-url,spm-pre,spm_cnt,pvid,_dev_id,_anony_id,_user_id,_user_nick,_sessio n_id
			},
			mobileLogin(env){
				if (window.location.href.indexOf("&ticket") == -1) {
					// 如果没有截取到ticket，就回跳登录页面  正式地址
					// window.location.href = `https://puser.zjzwfw.gov.cn/sso/${env}.do?action=oauth&scope=1&servicecode=BCDSGA_a2dbc846983174e522b97d8dbfc568fb&goto=https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2002238523/reserved/index.html`
					// 测试地址
					window.location.href = `https://puser.zjzwfw.gov.cn/sso/${env}.do?action=oauth&scope=1&servicecode=BCDSGA_a2dbc846983174e522b97d8dbfc568fb&goto=https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2002238523/lastTest/index.html`
				} else {
					let ticketStr = uni.getStorageSync("ticket") || "旧的ticket";
					// 如果有ticket，就截取ticket发送给后端，后端会返token回来
					let ticket = window.location.search ? window.location.search.substr(1).split("&").find(i => {
						return i.split("=")[0] == "ticket"
					}).split("=")[1] : "";
					// let ticket = '8a1189ba814448310181f6e8b9fa09ae-ticket';
					uni.setStorageSync("ticket", ticket);
					// uni.showLoading({
					// 	title: "加载中...",
					// });
					if (ticketStr != ticket) {
						this.$http.get('zhdt/getToken', {
							ticket
						}).then(res => {
							console.log(res, '获取token')
							if (res.data.success) {
								let token = res.data.data;
								uni.setStorageSync("token", token);
								uni.hideLoading();
								this.$http.get('zhdt/getUserInfo', {
									token
								}).then(info => {
									console.log(info.data.data, '获取用户信息')
									this.userInfo = info.data.data;
									uni.setStorageSync("userInfo", info.data.data);
									// 埋点
									let aplusUserInfo = {
										nick: info.data.data.name,
										id: info.data.data.userid,
									};
									this.$Aplus.userInfo(aplusUserInfo);
								})
							} else {
								uni.hideLoading();
								uni.showToast({
									title: "登录失败请重新登录",
									icon: "none"
								});
								setTimeout(() => {
									window.location.href =
										"https://puser.zjzwfw.gov.cn/sso/mobile.do?action=oauth&scope=1&servicecode=BCDSGA_a2dbc846983174e522b97d8dbfc568fb&goto=https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2002238523/reserved/index.html"
								}, 1000)
							}
						})
					} else {
						this.userInfo = uni.getStorageSync('userInfo')
					}
				}
			},
			setSwitch() {
				if (this.switch_state) {
					this.switch_state = false;
					window.document.querySelector('body').id = '';
				} else {
					this.switch_state = true;
					window.document.querySelector('body').id = 'elder';
				}
				console.log("1123123123")
			},
			goTel(tel) {
				ZWJSBridge.onReady(() => {
					ZWJSBridge.phoneCall({
						corpId: tel
					}).then((result) => {
						console.log(result);
					}).catch((error) => {
						console.log(error);
					});
				})
			},
			goHistory() {
				this.navTo("/pages/home/reserveHistory")
			},
			goNotice() {
				this.navTo("/pages/home/notice");
			},
			goTask(pageId) {
				this.navTo("/pages/home/getNumList", {
					pageId
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	.page-index {
		color: #3c3c3c;
		// background-color: #efeff4;
		padding-bottom: 160rpx;

		.user-info {
			text-align: right;
			background-color: #efeff4;

			text {
				display: inline-block;
				margin: 10rpx 10rpx 14rpx;
				font-size: 36rpx;
			}
		}

		.bottom {
			position: relative;
			width: 100%;
			background-color: #fff;
			padding: 10px;
			box-sizing: border-box;
			border-top: 10px solid #efeff4;

			.bottom-text {
				position: absolute;
				left: 0;
				top: 0;
				display: flex;
				flex-flow: column;
				text-align: center;
				width: 100%;
				color: #fff;
				font-size: 36rpx;

				text:nth-child(1) {
					margin: 90px 0 0 0;
				}

				text:nth-child(2) {
					margin: 15px 0 0 70px;
				}
			}

			.bottom-img {
				width: 100%;
			}
		}

		.server-item {
			width: 100%;
			display: flex;
			flex-flow: row;
			background-color: #fff;
			padding-bottom: 15px;

			.item {
				display: flex;
				flex-flow: column;
				width: 25%;
				text-align: center;

				image {
					width: 92rpx;
					height: 96rpx;
					margin: 20px auto 10px;
				}

				text {
					font-size: 28rpx;
				}
			}
		}

		.top {
			position: relative;
			width: 100%;
			background-color: #efeff4;

			.switch {
				position: absolute;
				right: 20rpx;
				top: 30rpx;
				width: 180rpx;
				height: 56rpx;
				line-height: 56rpx;
				color: #FFFFFF;
				font-size: 28rpx;
				border-radius: 99999rpx;
				background-color: #125bff;
				box-sizing: border-box;
				padding: 0 16rpx;
				z-index: 100;

				.txt {}

				.circular {
					position: absolute;
					right: 0;
					top: 0;
					box-sizing: border-box;
					width: 56rpx;
					height: 56rpx;
					background-color: #fff;
					box-shadow: 4rpx 4rpx 6rpx #a5a5a5;
					border-radius: 999999rpx;
					animation-name: leftRight;
					animation-duration: 300ms;
				}
			}

			.top-text {
				position: absolute;
				left: 0;
				top: 0;
				display: flex;
				flex-flow: column;
				text-align: center;
				width: 100%;
				color: #fff;

				text:nth-child(1) {
					font-size: 40rpx;
					margin: 40rpx 0;
				}

				text:nth-child(2) {
					font-size: 28rpx;
				}
			}

			.top-img {
				width: 100%;
			}
		}

		.footer {
			color: #808DA1;
			font-size: 24rpx;
			font-weight: 400;
			padding: 32rpx 0;
			text-align: center;
			line-height: 36rpx;

			text {
				display: block;

				.tel {
					color: #1492ff;
					display: inline-block;
				}
			}
		}

	}
</style>
